package com.xj.qq;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ChatRoom extends AppCompatActivity {

    private EditText chatList;
    private EditText userList;
    private EditText message;
    private EditText priUser;
    private Button sendBtn;
    private Button clearBtn;
    private Button backBtn;
    private CheckBox priChat;

    private Socket s;
    private InputStream inputStream;
    private OutputStream outputStream;
    private String Address;
    private String UserName;

    private RecvThread recvThread = new RecvThread();
    private RefleshHandler recvHandler = new RefleshHandler();
    private RecvRunable recvRunable = new RecvRunable();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chatroom_layout);
        chatList = (EditText) findViewById(R.id.Chat_List);
        userList = (EditText) findViewById(R.id.User_List);
        message = (EditText) findViewById(R.id.Send_Text);
        priUser = (EditText) findViewById(R.id.Pri_User);
        sendBtn = (Button) findViewById(R.id.Send_Btn);
        clearBtn = (Button) findViewById(R.id.Clear_Btn);
        backBtn = (Button) findViewById(R.id.chat_back);
        priChat = (CheckBox) findViewById(R.id.Pri_Chat);

        //设置 chatList,userList,priUser 只读
        chatList.setCursorVisible(false);
        chatList.setFocusable(false);
        chatList.setFocusableInTouchMode(false);
        userList.setCursorVisible(false);
        userList.setFocusable(false);
        userList.setFocusableInTouchMode(false);
        priUser.setCursorVisible(false);
        priUser.setFocusable(false);
        priUser.setFocusableInTouchMode(false);

        //sendBtn监听器
        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(message.getText().toString().length() == 0) {
                    Toast.makeText(ChatRoom.this, "不能发送空消息！", Toast.LENGTH_LONG).show();
                    return;
                } if(priChat.isChecked()){
                    if(priUser.getText().length() == 0){
                        Toast.makeText(ChatRoom.this, "请输入您要私聊的用户名！", Toast.LENGTH_LONG).show();
                        return;
                    }
                    try{
                        if(priUser.getText().toString().getBytes("GBK").length > 12){
                            Toast.makeText(ChatRoom.this, "用户名太长！", Toast.LENGTH_LONG).show();
                            return;
                        }
                    } catch (UnsupportedEncodingException e){
                        e.printStackTrace();
                    }
                    String sendText = "2\n" + UserName + "\n" + priUser.getText().toString() + "\n" + message.getText().toString();

                    try{
                        byte[] sendByte = sendText.getBytes("GBK");
                        outputStream.write(sendByte);
                    } catch (Exception e){
                        ChatRoom.this.finish();
                    }
                } else{
                    String sendText = "1\n" + UserName + "\n0\n" + message.getText().toString();
                    try{
                        byte[] sendByte = sendText.getBytes("GBK");
                        outputStream.write(sendByte);
                    } catch (Exception e){
                        ChatRoom.this.finish();
                    }
                }
                message.getText().clear();
            }
        });

        //clearBtn监听器
        clearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chatList.getText().clear();
            }
        });

        //priChat监听器
        priChat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    priUser.setCursorVisible(true);
                    priUser.setFocusable(true);
                    priUser.setFocusableInTouchMode(true);
                } else{
                    priUser.setCursorVisible(false);
                    priUser.setFocusable(false);
                    priUser.setFocusableInTouchMode(false);
                }
            }
        });

        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChatRoom.this, MainActivity.class);
                startActivity(intent);
            }
        });

        Intent intent = this.getIntent();
        Address = intent.getStringExtra("address");
        UserName = intent.getStringExtra("userName");
        //注册信息
        String loginInfo = "0\n" + UserName + "0\n" + "0";
        try{
            s = new Socket(Address, 3204);
            outputStream = s.getOutputStream();
            inputStream = s.getInputStream();
            outputStream.write(loginInfo.getBytes("GBK"));
            recvThread.start();
        } catch (UnknownHostException e){
            e.printStackTrace();
            ChatRoom.this.finish();
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    //接受线程
    public class RecvThread extends Thread{
        @Override
        public void run(){
            while(true){
                try{
                    if(inputStream.available() > 0){
                        //接收数据
                        byte[] recvByte = new byte[2048];
                        int recvCount;
                        if((recvCount = inputStream.read(recvByte)) < 0)
                            break;
                        int i = 0;
                        String[] cmd = recvByteToString(recvByte, recvCount);
                        for(i = 0; i < 10; i++){
                            if(cmd[i].compareTo("") != 0){
                                Message msg = recvHandler.obtainMessage(1, 1, 1, (Object)cmd[i]);
                                recvHandler.sendMessage(msg);
                            } else{
                                break;
                            }
                        }
                    }
                } catch (Exception e){
                    ChatRoom.this.finish();
                }
            }
        }
    }

    //声明刷新聊天记录handler
    public class RefleshHandler extends Handler{
        @Override
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            if(msg.what != 1)
                return;
            String str = (String)msg.obj;
            String[] splitStr = str.split("\n", 4);
            if(splitStr.length != 4)
                return;
            String type = splitStr[0];
            String getUser = splitStr[1];
            String setUser = splitStr[2];
            String data = splitStr[3];

            //获取当前时间
            SimpleDateFormat date = new SimpleDateFormat("HH:mm:ss");
            String time = date.format(new Date());

            //type == 1, 群发消息
            if(type.compareTo("1") == 0){
                chatList.append(time + " ");
                chatList.append(getUser + "对所有人说：");
                chatList.append(data + "\n");
            }

            //type == 2, 进行私聊
            if(type.compareTo("2") == 0){
                if(getUser.compareTo(UserName) == setUser.compareTo(UserName)){
                    chatList.append(time + " ");
                    chatList.append("您对自己说：");
                    chatList.append(data + "\n");
                } if(getUser.compareTo(UserName) == 0){
                    chatList.append(time + " ");
                    chatList.append("您对" + setUser + "说：");
                    chatList.append(data + "\n");
                } if(setUser.compareTo(UserName) == 0){
                    chatList.append(time + " ");
                    chatList.append(setUser + "对您说：");
                    chatList.append(data + "\n");
                }
            }

            //type == 10, 注册成功
            if (type.compareTo("10") == 0){
                chatList.append(time + " ");
                chatList.append("来自服务器的消息：");
                chatList.append(data + "\n");
            }

            //type == 11, 注册失败
            if (type.compareTo("11") == 0){
                chatList.append(time + " ");
                chatList.append("来自服务器的消息：");
                chatList.append(data + "\n");
            }

            //type == 12, 更新用户列表
            if (type.compareTo("12") == 0)
            {
                userList.getText().clear();
                userList.append(data);
                userList.append("更新时间：\n" + time);
            }

            //type == 13, 进入聊天室
            if (type.compareTo("13") == 0)
            {
                chatList.append(time + " ");
                chatList.append(data + "\n");
            }

            //type == 14, 发送的私聊信息出错
            if (type.compareTo("14") == 0)
            {
                chatList.append(time + " ");
                chatList.append(data + "\n");
            }
        }
    }

    //接收由handler处理后的信息
    public class RecvRunable implements Runnable{
        @Override
        public void run(){
            try{
                if(inputStream.available() > 0){
                    byte[] receiverBuff = new byte[2048];
                    if(inputStream.read(receiverBuff) < 0)
                        return;
                    String data = new String(receiverBuff, 0, recvCount(receiverBuff), "GBK");
                    System.out.println(data);
                    System.out.println(data.length());
                    chatList.append(data);
                }
                recvHandler.postDelayed(recvRunable, 2000);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onStop(){
        super.onStop();
        try{
            s.close();
        } catch (IOException e){
            e.printStackTrace();
        }
        Toast.makeText(ChatRoom.this, "已和服务器断开连接！", Toast.LENGTH_LONG).show();
        recvThread.stop();
    }
    protected void onDestory(){
        super.onDestroy();
        try{
            s.close();
        } catch (IOException e){
            e.printStackTrace();
        }
        recvThread.stop();
    }

    //从 inputStream 中获取命令字符串数组
    public static String[] recvByteToString(byte[] str, int recvCount){
        String[] cmdArray = new String[10];
        int i = recvCount, k, strCount = 0, offset = 0;
        for(k = 0; k < i; k++){
            if(str[k] == 0){
                try{
                    cmdArray[strCount] = new String(str, offset, k - offset, "GBK");
                } catch (UnsupportedEncodingException e){
                    e.printStackTrace();
                }
                strCount++;
                offset = k + 1;
            }
        }
        return cmdArray;
    }

    //计算从 inputStream 中读取的字符数
    public static int recvCount(byte[] cmd){
        int i;
        for(i = 0; i < cmd.length; i++){
            if(cmd[i] == 0)
                return 0;
        }
        return cmd.length;
    }

    //计算 cmd 的个数
    public static int cmdCount(String[] cmdArray) {
        String str = new String();
        int i;
        for (i = 0; i < cmdArray.length; i++) {
            if (str.compareTo(cmdArray[i]) == 0)
                return i;
        }
        return cmdArray.length;
    }
}
